package android.cmpe451.group7.activity;

import java.lang.reflect.Type;
import java.util.List;

import com.google.gson.reflect.TypeToken;

import android.cmpe451.group7.activity.R;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.cmpe451.group7.dbrequest.RetrieveJSONTask;
import android.cmpe451.group7.dbrequest.WebServiceResponse;
import android.cmpe451.group7.entity.Place;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Shows search results on a view.
 * 
 */
public class SearchResultsActivity extends Activity {
	public final static String EXTRA_MESSAGE = "com.example.ourcity_android.MESSAGE";
	private ListView listView;
	private SearchResultsArrayAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_results);
		// Show the Up button in the action bar.
		setupActionBar();

		Intent intent = getIntent();
		String requestUrl = intent.getStringExtra(SearchActivity.EXTRA_MESSAGE);
		listView = (ListView) findViewById(R.id.searchResultsListView);

		new PlaceSearchTask(this).execute(requestUrl);

		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, final View view,
					int position, long id) {
				Intent i = new Intent(getApplicationContext(),
						PlaceDetailActivity.class);
				SearchResultsArrayAdapter adapter = (SearchResultsArrayAdapter) parent
						.getAdapter();
				Place data = adapter.getItem(position);
				Toast.makeText(getBaseContext(),
						position + " - " + data.getPlaceName(),
						Toast.LENGTH_LONG).show();
				i.putExtra(EXTRA_MESSAGE, Long.toString(data.getPlaceID()));
				Bundle bundle = new Bundle();
				bundle.putSerializable("place", data);
				i.putExtras(bundle);
				startActivity(i);
			}

		});
	}

	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.display_message, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * Creates an array adapter and put comments inside with their text,
	 * description and image.
	 * 
	 */
	private class SearchResultsArrayAdapter extends ArrayAdapter<Place> {
		public SearchResultsArrayAdapter(Context context,
				int textViewResourceId, List<Place> dataList) {
			super(context, textViewResourceId, dataList);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = (LayoutInflater) super.getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View rowView = inflater.inflate(R.layout.base_adapter, parent,
					false);
			TextView textView = (TextView) rowView
					.findViewById(R.id.listViewText);
			ImageView imageView = (ImageView) rowView
					.findViewById(R.id.listViewIcon);

			textView.setText(super.getItem(position).getPlaceName());
			imageView.setImageResource(R.drawable.placeicon);

			return rowView;
		}
	}

	/**
	 * Searches places.
	 * 
	 */
	private class PlaceSearchTask extends RetrieveJSONTask<Place> {
		ProgressDialog progressDialog;

		public PlaceSearchTask(Activity activity) {
			super(activity);
		}

		@Override
		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(activity, "",
					"getting places...");
		}

		@Override
		protected WebServiceResponse<Place> doInBackground(String... params) {
			Type type = new TypeToken<WebServiceResponse<Place>>() {
			}.getType();
			return super.doInBackground(type, params);
		}

		@Override
		protected void onPostExecute(WebServiceResponse<Place> gsonObject) {
			progressDialog.dismiss();
			if (gsonObject != null) {
				adapter = new SearchResultsArrayAdapter(activity,
						android.R.layout.simple_list_item_1, gsonObject.data);
				adapter.notifyDataSetChanged();
				listView.setAdapter(adapter);
			}
		}

	}
}
